#include "UdpServer.hpp"
#include <memory>
// 客户端一定要先知道服务器的ip地址和端口号
//  ./udp_client server_ip server_port
//  ./udp_client 127.0.0.1 8888
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << "server_ip server_port" << std::endl;
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(1);
    }

    // 客户端的端口号 一般不让用户自己设定，而是让client os随机选择
    // client不需要显式bing自己的IP地址和端口号
    // client在首次向服务器发送数据的时候，os会自动给client bind他自己的ip地址和端口号

    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str()); // 需要4字节ip 需要网络序列的ip

    while (1)
    {
        std::string line;
        std::cout << "Please Enter# ";
        std::getline(std::cin, line);

        std::cout << "line message is@ " << line << std::endl;

        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof server); // 要知道发给谁
        if (n > 0)
        {
            struct sockaddr_in temp;
            socklen_t len = sizeof temp;

            char buffer[1024];
            int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len); // 接收消息 从temp读 len 长度的消息 读到buffer中
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                std::cout << "recvfrom error" << std::endl;
                break;
            }
        }
        else
        {
            std::cout << "sendto error" << std::endl;
            break;
        }
    }

    ::close(sockfd);
    return 0;
}